package parser

import (
	"aqielife.cn/spider/singleSpider/zhenai/model"
	"log"
	"regexp"
	"strconv"
)

// 预编译
var genderRe = regexp.MustCompile(`<td><span class="label">性别：</span><span field="">([^<]+)</span></td>`)
var ageRe = regexp.MustCompile(`<td><span class="label">年龄：</span>([\d]+)岁</td>`)

var heightRe = regexp.MustCompile(`<td><span class="label">身高：</span>([\d]+)[\w]+</td>`)
var weightRe = regexp.MustCompile(`<td><span class="label">体重：</span><span field="">([\d]+)[\w]+</span></td>`)

var incomeRe = regexp.MustCompile(`<td><span class="label">月收入：</span>([^<]+)</td>`)
var constellationRe = regexp.MustCompile(`<td><span class="label">星座：</span>([^<]+)</td>`)

var marriageRe = regexp.MustCompile(`<td><span class="label">婚况：</span>([^<]+)</td>`)
var educationRe = regexp.MustCompile(`<td><span class="label">学历：</span>([^<]+)</td>`)

var residenceRe = regexp.MustCompile(`<td><span class="label">籍贯：</span>([^<]+)</td>`)
var workplaceRe = regexp.MustCompile(`<td><span class="label">工作地：</span>([^<]+)</td>`)

var companyRe = regexp.MustCompile(`<td><span class="label">公司：</span><span field="">([^<]+)</span></td>`)
var occupationRe = regexp.MustCompile(`<td><span class="label">职业： </span>([^<]+)</td>`)

var houseRe = regexp.MustCompile(`<td><span class="label">住房条件：</span><span field="">([^<]+)</span></td>`)
var carRe = regexp.MustCompile(`<td><span class="label">是否购车：</span><span field="">([^<]+)</span></td>`)

// http://album.zhenai.com/u/1427538961   用户信息页
func ParseProfile(contents []byte, name string) model.ParseResult {
	profile := model.Profile{}
	profile.Name = name

	profile.Gender = extractString(contents, genderRe)
	profile.Age = extractInt(contents, ageRe)

	profile.Height = extractInt(contents, weightRe)

	profile.Weight = extractInt(contents, weightRe)

	profile.Income = extractString(contents, incomeRe)
	profile.Constellation = extractString(contents, constellationRe) // 星座

	profile.Marriage = extractString(contents, marriageRe)
	profile.Education = extractString(contents, educationRe)

	profile.Residence = extractString(contents, residenceRe) // 籍贯
	profile.Workplace = extractString(contents, workplaceRe) // 工作地

	profile.Company = extractString(contents, companyRe)
	profile.Occupation = extractString(contents, occupationRe)

	profile.House = extractString(contents, houseRe)
	profile.Car = extractString(contents, carRe)

	result := model.ParseResult{
		Items: []interface{}{profile},
	}
	return result
}

func extractInt(contents []byte, re *regexp.Regexp) int {
	s := extractString(contents, re)
	if s == "" {
		return 0
	} else {
		if weight, err := strconv.Atoi(s); err == nil {
			return weight
		} else {
			log.Printf("weight error %v", err)
			return 0
		}
	}
}

func extractString(contents []byte, re *regexp.Regexp) string {
	// 只找第一个
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}
